<?php

namespace model;

use root\base\model;

class images extends model
{
	//关联查找一条数据
	public function findData()
	{
		$db = $this->db();
		$where['id'] = $_GET['id'];
		return $db->table('images')->where($where)->find();
	}
	//查询列表
	public function selectData($limit)
	{
		$db = $this->db();
		$where['status'] = 1;
		return $db->table('images')->where($where)->limit($limit)->cache(600)->Order('id DESC')->select();
	}

	//添加数据
	public function insertData()
	{
		if (empty($_POST['title']))
			return ['status' => 0, 'msg' => '请填写必要数据'];
		$db = $this->db('images');
		$data = [
			'title' => varFilter($_POST['title']),
			'img' => varFilter($_POST['img']),
			'auther' => varFilter($_POST['auther']),
			'content' => varFilter($_POST['content']),
			'time' => date('Y-m-d H:i:s', time()),
			'status' => $_POST['status'],
		];
		$re_key = $db->insert($data);
		if ($re_key) {
			//写入日志
			insertSqlLog("添加图集 ID：" . $re_key);

			return ['key' => $re_key, 'status' => 1, 'msg' => '添加成功'];
		} else {
			return ['status' => 0, 'msg' => '数据错误！添加失败'];
		}
	}
	//更新数据
	public function updateData()
	{
		if (empty($_POST['title']))
			return  ['status' => 0, 'msg' => '请填写必要数据'];
		$db = $this->db();
		$where['id'] = $_POST['id'];
		$data = [
			'title' => varFilter($_POST['title']),
			'img' => varFilter($_POST['img']),
			'auther' => varFilter($_POST['auther']),
			'content' => varFilter($_POST['content']),
			'status' => $_POST['status'],
		];
		$re_key = $db->table('images')->Where($where)->Update($data);
		if ($re_key) {
			//写入日志
			insertSqlLog("修改图集 ID：" . $_POST['id']);

			return ['status' => 1, 'msg' => '修改成功'];
		} else {
			return ['status' => 0, 'msg' => '数据没有变化'];
		}
	}

	//判断删除一条数据
	public function deleteOneData()
	{
		$db = $this->db();
		$find['aid'] = $_POST['id'];
		$find = $db->table('images_image')->where($find)->find();
		if ($find) {
			return false;
		} else {
			$where['id'] = $_POST['id'];
			insertSqlLog("删除图集 ID：" . $_POST['id']);//写入日志
			return $db->table('images')->where($where)->Delete();
		}
	}

	//设置状态
	public function switchStatus()
	{
		$db = $this->db();
		$where['id'] = $_POST['id'];
		$data = [
			'status' => $_POST['status']
		];
		//写入日志
		insertSqlLog("设置图集状态 ID：" . $_POST['id']);

		return $db->table('images')->where($where)->Update($data);
	}

	//获取数据并分页
	public function jsonPageSelect()
	{
		$db = $this->db();
		$p = intval($_GET['page'] ?? 0) ?: 1;
		$num = intval($_GET['limit'] ?? 0) ?: 15;

		$page = ['num' => $num, 'p' => $p, 'return' => true];
		$result['data'] = $db->table('images')->Page($page)->order('id DESC')->select();
		$result['page'] = $db->getPage();
		return $result;
	}
}
